package services

import (
	"fmt"
	"sync"
)

var (
	UserClientService = userClientService{
		user_clients:make(map[uint][]*Client),
	}
)

//用户id关联client
type userClientService struct {
	//用户连接
	user_clients map[uint][]*Client
	lock sync.RWMutex
}

//clearClients 清理该用户下的无效连接
func (this *userClientService) clearClients(uid uint) {
	if uid == 0 {
		return
	}

	this.lock.Lock()
	defer this.lock.Unlock()

	clients := this.user_clients[uid]
	if clients == nil || len(clients) == 0{
		return
	}

	//开始清理
	newClients := make([]*Client, 0)
	for _,client := range clients {
		if client.status == 0 {
			newClients = append(newClients, client)
		}
	}

	//如果全部清理则删除该用户
	if len(newClients) == 0 {
		delete(this.user_clients, uid)
		return
	}

	//替换新连接池
	this.user_clients[uid] = newClients
}

//AddUser 新增用户
func (this *userClientService) AddUser(uid uint, c *Client) (err error) {
	if uid == 0 {
		err = fmt.Errorf("缺少uid")
		return
	}

	//添加客户端连接
	this.lock.Lock()
	defer this.lock.Unlock()

	clients := this.user_clients[uid]
	if clients == nil {
		clients = make([]*Client, 0)
	}
	clients = append(clients, c)
	this.user_clients[uid] = clients
	return nil
}

//IsOnline 用户是否在线
func (this *userClientService) IsOnline(uid uint) bool {
	onlineClients := this.GetOnlineClients(uid)
	if len(onlineClients) == 0 {
		return false
	}
	return true
}

//GetOnlineClients 获取在线的client
func (this *userClientService) GetOnlineClients(uid uint) []*Client {
	onlineClients := make([]*Client, 0)

	this.lock.RLock()
	clients := this.user_clients[uid]
	this.lock.RUnlock()

	if clients == nil {
		return onlineClients
	}

	for _,v := range clients {
		if v.status == 0 {
			onlineClients = append(onlineClients, v)
		}
	}
	return onlineClients
}

//WriteMqMessage 给指定用户发送业务消息队列的消息
func (this *userClientService) WriteMessage(uid uint, action string, data map[string]interface{}) {
	clients := this.GetOnlineClients(uid)
	for _, v := range clients {
		v.WriteReturn(action, data)
	}
}

func (this *userClientService) GetOnlines() map[uint][]*Client {
	return this.user_clients
}


